import React from 'react'

import { Alert, message } from 'antd';
import { ProFormText, LoginForm } from '@ant-design/pro-components';
import { useIntl, history, FormattedMessage, useModel } from 'umi';

import { CommonApi, UserApi } from '@/services/admin';
import * as Storage from '@/services/storage';

import styles from './index.less';

const Login: React.FC = () => {
  const intl = useIntl();

  const handleSubmit = async (values: API.LoginParams) => {
    UserApi.login({...values}).then(result=>{
      console.log("login msg:", result);
      if(result.success){
        const defaultLoginSuccessMessage = intl.formatMessage({
          id: 'pages.login.success',
          defaultMessage: '登录成功！',
        });
        message.success(defaultLoginSuccessMessage);

        Storage.setItem(Storage.KEY_TOKEN, result.data!.token!);
        if (!history) return;
        history.push('/');
        return;
      }else{
        throw Error
      }
    }).catch(error=>{
      const defaultLoginFailureMessage = intl.formatMessage({
        id: 'pages.login.failure',
        defaultMessage: '登录失败，请重试！',
      });
      message.error(defaultLoginFailureMessage);
    })
  }

  return (
    <div className={styles.container}>
      <div className={styles.content}>
        <LoginForm
          title="I-Cloud"
          subTitle={intl.formatMessage({ id: 'pages.layouts.userLayout.title' })}
          onFinish={async (values) => {
            await handleSubmit(values as API.LoginParams);
          }}
        >
          <>
            <ProFormText name="username"
              placeholder={intl.formatMessage({
                id: 'pages.login.username.placeholder',
                defaultMessage: '用户名',
              })}
              rules={[{
                required: true,
                message: (
                  <FormattedMessage
                    id="pages.login.username.required"
                    defaultMessage="请输入用户名!"
                  />
                ),
              }]} />
            <ProFormText.Password name="password"
              placeholder={intl.formatMessage({
                id: 'pages.login.password.placeholder',
                defaultMessage: '密码',
              })}
              rules={[{
                required: true,
                message: (
                  <FormattedMessage
                    id="pages.login.password.required"
                    defaultMessage="请输入密码！"
                  />
                ),
              }]} />
          </>
        </LoginForm>
      </div>
    </div>
  )
}

export default Login;
